﻿using eFatura.Utility;
using Extensions;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text.RegularExpressions;

namespace eFatura
{
    public partial class XMLInvoice : XForm
    {
        public XMLInvoice()
        {
            InitializeComponent();
        }

        private void btnScript_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog o = new System.Windows.Forms.OpenFileDialog();
            o.ShowDialog();

            string input = File.ReadAllText(o.FileName);
            string pattern = @"(</?)(\w+:)";

            string output = Regex.Replace(input, pattern, "$1");

            StringReader reader = new StringReader(output);
            DataSet ds = new DataSet();
            ds.ReadXml(reader);

            string sql = "";
            foreach (DataTable dt in ds.Tables)
                sql += "\r\n" + CreateTABLE("EF_" + dt.TableName, dt);

            txt.Text = sql;
        }

        public static string CreateTABLE(string tableName, DataTable table)
        {
            if (!"EF_Invoice;EF_LineExtensionAmount;EF_TaxInclusiveAmount;EF_AllowanceTotalAmount;EF_LegalMonetaryTotal;EF_Note;EF_PartyName;EF_ID;EF_PayableAmount;EF_TaxTotal;EF_TaxAmount;EF_InvoicedQuantity;EF_Item;EF_Price;EF_PriceAmount;EF_TaxScheme;EF_TaxCategory;EF_TaxSubtotal".Contains(tableName))
                return "";

            string sqlsc;
            sqlsc = "CREATE TABLE " + tableName + "(";

            sqlsc += "\n [IDX] int IDENTITY(1,1),";

            for (int i = 0; i < table.Columns.Count; i++)
            {
                sqlsc += "\n [" + table.Columns[i].ColumnName + "] ";
                string columnType = table.Columns[i].DataType.ToString();
                switch (columnType)
                {
                    case "System.Int32":
                        sqlsc += " int ";
                        break;
                    case "System.Int64":
                        sqlsc += " bigint ";
                        break;
                    case "System.Int16":
                        sqlsc += " smallint";
                        break;
                    case "System.Byte":
                        sqlsc += " tinyint";
                        break;
                    case "System.Decimal":
                        sqlsc += " decimal ";
                        break;
                    case "System.DateTime":
                        sqlsc += " datetime ";
                        break;
                    case "System.String":
                    default:
                        sqlsc += string.Format(" nvarchar({0}) ", table.Columns[i].MaxLength == -1 ? "max" : table.Columns[i].MaxLength.ToString());
                        break;
                }

                if (!table.Columns[i].AllowDBNull)
                    sqlsc += " NOT NULL ";
                sqlsc += ",";
            }
            return sqlsc.Substring(0, sqlsc.Length - 1) + "\n)" + "ALTER TABLE " + tableName + " ADD CONSTRAINT PK_" + tableName + " PRIMARY KEY CLUSTERED (IDX)";
        }

        private void btnKontrol_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Kontrol(false);
        }

        private void Kontrol(bool aktar)
        {
            txt.Text = "";

            System.Windows.Forms.FolderBrowserDialog f = new System.Windows.Forms.FolderBrowserDialog();

            f.ShowDialog();

            string[] files = Directory.GetFiles(f.SelectedPath);


            bool ok = true;
            foreach (string file in files)
            {

                string input = File.ReadAllText(file);
                string pattern = @"(</?)(\w+:)";

                string output = Regex.Replace(input, pattern, "$1");

                StringReader reader = new StringReader(output);


                //reader = new StringReader(input);

                DataSet dsX = new DataSet();
                dsX.ReadXml(reader);

                txt.Text += Environment.NewLine + file;
                foreach (DataTable table in dsX.Tables)
                {

                    while (table.ChildRelations.Count > 0)
                    {
                        var relation = table.ChildRelations[0];
                        dsX.Tables[relation.ChildTable.TableName].Constraints.Remove(relation.RelationName);
                        dsX.Relations.Remove(relation);
                    }

                    while (table.ParentRelations.Count > 0)
                    {
                        dsX.Relations.Remove(table.ParentRelations[0]);
                    }

                    table.Constraints.Clear();

                }

                dsX.Relations.Clear();



                foreach (DataTable x in dsX.Tables)
                {
                    if (!"EF_Invoice;EF_LineExtensionAmount;EF_TaxInclusiveAmount;EF_AllowanceTotalAmount;EF_LegalMonetaryTotal;EF_Note;EF_PartyName;EF_ID;EF_PayableAmount;EF_TaxTotal;EF_TaxAmount;EF_InvoicedQuantity;EF_Item;EF_Price;EF_PriceAmount;EF_TaxScheme;EF_TaxCategory;EF_TaxSubtotal".Contains("EF_" + x.TableName))
                        continue;

                    DataTable dt = x.Copy();

                    try
                    {
                        dt.Columns.Add("IDX", typeof(int));

                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(dt.TableName + ": HATALI");

                        DataTable result = new DataTable();

                        foreach (DataColumn c in dt.Columns)
                        {
                            result.Columns.Add(c.ColumnName, typeof(string));
                        }
                        DataColumn dc = result.Columns["IDX"];
                        if (dc == null)
                            dc = new DataColumn("IDX"); // table.Columns.Add("IdentityId", typeof(int));
                        dc.AutoIncrement = true;
                        dc.AutoIncrementSeed = 1;
                        dc.AutoIncrementStep = 1;

                        if (!result.Columns.Contains("IDX"))
                            result.Columns.Add(dc);

                        foreach (DataRow dr in dt.Rows)
                        {
                            result.Rows.Add(dr.ItemArray);
                        }


                        result.TableName = dt.TableName;

                        dt = result;
                    }

                    System.Diagnostics.Debug.WriteLine(dt.TableName);

                    for (int i = 1; i < dt.Rows.Count + 1; i++)
                        dt.Rows[i - 1]["IDX"] = i;


                    dt.PrimaryKey = new DataColumn[] { dt.Columns["IDX"] };

                    DataTable dx = AppSession.DataManager.ExecuteDataTableByQuery("select top 0 * from EF_" + dt.TableName);

                    for (int i = dt.Columns.Count - 1; i > -1; i--)
                    {
                        if (dx.Columns[dt.Columns[i].ColumnName] == null)
                            dt.Columns.Remove(dt.Columns[i]);
                    }








                    try
                    {
                        dt.PrimaryKey = new DataColumn[] { dt.Columns["IDX"] };
                        gv.Init(dt);
                        //GridManager.GetManager(gv).PK = "IDX";
                        List<string> cols = new List<string>();
                        foreach (DataColumn dc in dt.Columns)
                            cols.Add("[" + dc.ColumnName + "]");

                        gv.Update(string.Join(",", cols), "EF_" + dt.TableName);

                    }
                    catch (Exception ex)
                    {
                        ok = false;
                        break;
                    }
                }

                FileInfo fi = new FileInfo(file);
                Directory.CreateDirectory(fi.Directory + "\\OK");
                Directory.CreateDirectory(fi.Directory + "\\ERROR");
                string newPath = fi.DirectoryName + "\\ERROR\\" + fi.Name;

                if (ok)
                {
                    fi.MoveTo(newPath.Replace("ERROR", "OK"));
                    if (aktar)
                        AppSession.DataManager.ExecuteNonQuery("GetFaturaFromXml");
                }
                else
                    fi.MoveTo(newPath);

            }
        }

        private void XMLInvoice_Load(object sender, EventArgs e)
        {
            MainToolbar.Visible = true;
        }

        private void btnAktar_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //fatura url leri innovadan alınıp EF_URL [Kurum,FaturaNo,URL] tablosunda kaydedilmeli.

            //    CREATE TABLE [dbo].[EF_URL](
            //    [Kurum] [int] NULL,
            //    [FaturaNo] [varchar](max) NULL,
            //    [URL] [varchar](max) NULL
            //) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

            Kontrol(true);
        }
    }
}
